package fx;

import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONUtil;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class Fetcher {
    private static final String searchUrl = "https://api.imjad.cn/cloudmusic/?type=search&search_type=1&s=";
    private static final String searchUrlById = "https://api.imjad.cn/cloudmusic/?type=song&id=";
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .callTimeout(10, TimeUnit.SECONDS)
            .build();

    public static void search(String word) throws IOException {
        Call call = client.newCall(new Request.Builder()
                .get()
                .url(searchUrl + URLUtil.encode(word)).build());
        Response response = call.execute();
        String s = new String(response.body().bytes());
        System.out.println(s);
        Object byPath = JSONUtil.parseObj(s).getByPath("$.data.[0].url");
        System.out.println(byPath);
    }

    public static String searchById(Long id) throws IOException {
        Call call = client.newCall(new Request.Builder()
                .get()
                .url(searchUrlById + id + "&br=128000").build());
        Response response = call.execute();
        String s = new String(response.body().bytes());
        System.out.println(s);
        Object byPath = JSONUtil.parseObj(s).getByPath("$.data.[0].url");
        System.out.println(byPath);
        String s1 = ((String) byPath).replaceAll("\", ", "");
        return s1;
    }
}
